package com.cff.springbootwork.actuator.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import com.fasterxml.jackson.databind.ObjectMapper;

@WebFilter(urlPatterns = "/actuator/*", filterName = "actuatorPermissionFilter")
@Order(1) // 指定过滤器的执行顺序,值越大越靠后执行
public class ActuatorPermissionFilter implements Filter {
	private String excludePath = "actuator/super";
	@Value("${actuator.filter.switch}")
	Boolean actuatorSwitch;

	@Override
	public void init(FilterConfig filterConfig) {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		if (actuatorSwitch && !(request.getRequestURI().endsWith(excludePath)
				&& request.getMethod().equals(HttpMethod.POST.toString()))) {
			Object user = request.getSession().getAttribute("superUser");
			if (user == null) {
				// 未登录,返回数据
				ObjectMapper mapper = new ObjectMapper();
				response.setStatus(HttpStatus.OK.value());
				response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
				mapper.writeValue(response.getWriter(), "您没有权限访问该接口，请使用自定义的登录接口设置superUser后使用！");
				return;
			}
		}
		filterChain.doFilter(servletRequest, servletResponse);

	}

	@Override
	public void destroy() {
	}

}
